package cn.fl.project.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.preloan.IProjectProductMortgateService;
import cn.fl.preloan.dto.*;
import cn.fl.preloan.enums.PreloanResultCodeEnum;
import cn.fl.project.dto.PrjPrdDtlDTO;
import cn.fl.project.vo.PrjPrdLicOrgVO;
import cn.fl.upload.constant.UploadConstant;

import com.google.common.base.Optional;
import cn.fl.commons.result.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlDatCfgQueryCondition;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.comm.facade.upload.dto.SysUlFilesRecDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.api.ICheckVehicleRegistrationApiService;
import cn.fl.project.api.IProjectQueryApiService;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.condition.PrjPrdMtgQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.constant.PrjPrdBscInfoConstant;
import cn.fl.project.constant.PrjPrdDtlConstant;
import cn.fl.project.constant.PrjPrdMtgConstant;
import cn.fl.project.dto.PrjBscInfoDTO;
import cn.fl.project.service.IPrjPrdMtgService;
import cn.fl.project.service.IProjectApiService;
import cn.fl.project.transform.PrjPrdMtgVOTransform;
import cn.fl.project.vo.PrjPrdMtgVO;
import cn.fl.system.service.ISysUlDatCfgService;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.vo.SysUlDatCfgVO;
import cn.fl.system.vo.SysUlFilesRecVO;

/**
 * @Description: 项目产品抵押信息表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class PrjPrdMtgServiceImpl implements IPrjPrdMtgService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IPrjPrdMtgService.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IProjectApiService projectApiService;
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	private IUploadApiService uploadApiService;
	@Autowired
	private ISysUlDatCfgService sysUlDatCfgService;
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;
	@Autowired
	private IProjectQueryApiService projectQueryApiService;
	@Autowired
	private ICheckVehicleRegistrationApiService  checkVehicleRegistrationApiService;
	@Autowired
	private IProjectProductMortgateService mortgateService;
	@Override
	public PrjPrdMtgVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		PrjPrdMtgDetailRequest request = new PrjPrdMtgDetailRequest();
		request.setId(id);
		request.setSysCd(CurrentThreadContext.getCurrentSysCd());
		request.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		ResponseData response = this.mortgateService.selectPrjPrdMtgById(request);
		PrjPrdMtgVO prjPrdMtgVO =null;
		PrjPrdLicOrgVO licOr = null;
		if(PreloanResultCodeEnum.SUCCESS.getCode().equals(response.getCode())){
			prjPrdMtgVO = new PrjPrdMtgVO();
			licOr = new PrjPrdLicOrgVO();
			PrjPrdMtgDTO prjPrdMtgDTO = (PrjPrdMtgDTO)response.getData();
			if(null != prjPrdMtgDTO){
				BeanUtils.copyProperties(prjPrdMtgDTO,prjPrdMtgVO);
				if(null != prjPrdMtgDTO.getLicOrg()){
					BeanUtils.copyProperties(prjPrdMtgDTO.getLicOrg(),licOr);
				}
			}
			prjPrdMtgVO.setLicOrg(licOr);
		}
		return prjPrdMtgVO;
	}

	@Override
	public Long add(PrjPrdMtgVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		PrjPrdMtgDTO dto = new PrjPrdMtgDTO();
		BeanUtils.copyProperties(entity,dto);
        ResponseData response = this.mortgateService.add(dto);
        Long id = null;
		if(ResponseData.SUCCESS_CODE.equals(response.getCode()) &&
				null != response.getData()){
			id = (Long)response.getData();
			List<SysUlFilesRecVO> fileList = entity.getFileList();
//			List<SysUlFilesRecDTO> dtoFileList = new ArrayList<SysUlFilesRecDTO>();
			if(CollectionUtils.isNotEmpty(fileList)){
				 String orgCd = PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG;
					//查询项目的事业部
					PrjPrdDtlDTO dtl = this.projectApiService.selectPrjPrdDtlById(entity.getId());
					if(null!=dtl){
						Long prjId = dtl.getPrjId();
						if (prjId == null && entity.getPrjId() != null) {
							prjId = entity.getPrjId();
						}
						PrjBscInfoDTO prjBsc = 	this.projectApiService.selectPrjBscInfoById(prjId, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
						if(null!=prjBsc){
							orgCd = prjBsc.getBuOrgCd();
						}
					}
					//查询文件主code
					SysUlDatCfgQueryCondition qc = new SysUlDatCfgQueryCondition();
							List<String> codeList = new ArrayList<String>();
							codeList.add(PrjPrdMtgConstant.PRJ_PRD_MTG_FILE_CODE);
							qc.setCfgCdList(codeList);
					      qc.setOrgCd(orgCd);
						qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
						String  sysCdStr = "";
						String orgCdStr = "";
						List<SysUlDatCfgVO> cfgList = sysUlDatCfgService.searchList(qc);
			/*			List<SysUlDatCfgDtlVO> dtlList = cfgList.get(0).getSysUlDatCfgDtlVOList();
						for (SysUlDatCfgDtlVO sysUlDatCfgDtlVO : dtlList) {
							if(sysUlDatCfgDtlVO.getCfgDtlCd().equals(PrjPrdMtgConstant.PRJ_PRD_MTG_FILE_DETAIL_CODE)){
								sysCdStr = sysUlDatCfgDtlVO.getSysCd();
								orgCdStr = sysUlDatCfgDtlVO.getOrgCd();
								break;
							}
						}*/
						sysCdStr = cfgList.get(0).getSysCd();
						orgCdStr = cfgList.get(0).getOrgCd();
				for (SysUlFilesRecVO sysUlFilesRecVO : fileList) {
					sysUlFilesRecVO.setPkId(String.valueOf(id));
					sysUlFilesRecVO.setTabNm("PRJ_PRD_MTG_INFO");
					sysUlFilesRecVO.setIsDel(BaseConstant.IS_YESNO_NO);
					sysUlFilesRecVO.setOrgCd(orgCdStr);
					sysUlFilesRecVO.setSysCd(sysCdStr);
					sysUlFilesRecVO.setCfgCd(PrjPrdMtgConstant.PRJ_PRD_MTG_FILE_CODE);
					sysUlFilesRecVO.setCfgDtlCd(PrjPrdMtgConstant.PRJ_PRD_MTG_FILE_DETAIL_CODE);
					sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH)+sysUlFilesRecVO.getFilePath());

					/*SysUlFilesRecDTO dto = SysUlFilesRecVOTransform.toDTO(sysUlFilesRecVO);
					dtoFileList.add(dto);*/
					this.sysUlFilesRecService.add(sysUlFilesRecVO);
				}
			}
		}
		return id;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
    		BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		};
		return projectApiService.removePrjPrdMtgByIds(ids);
    }

	@Override
	public boolean modify(PrjPrdMtgVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		PrjPrdMtgDTO prjPrdMtgDTO = new PrjPrdMtgDTO();
		BeanUtils.copyProperties(entity,prjPrdMtgDTO);
		long startTime = System.currentTimeMillis();
		BaseLogUtils.info(logger, "modify", "调用贷前服务修改抵押信息!", CurrentThreadContext.getCurrentUserName());
		ResponseData response= mortgateService.modifyProjProdMortgage(prjPrdMtgDTO);
		BaseLogUtils.info(logger, "modify", "调用贷前服务修改抵押信息结束,耗时："+(System.currentTimeMillis()-startTime), CurrentThreadContext.getCurrentUserName());
		if(!PreloanResultCodeEnum.SUCCESS.getCode().equals(response.getCode())){
			BaseLogUtils.error(logger, "modify", "调用贷前服务修改抵押信息返回失败!errorMsg = "+response.getMessage(), CurrentThreadContext.getCurrentUserName());
			return false;
		}
		try {
			String orgCd = PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG;
			//查询项目的事业部
			PrjPrdDtlDTO dtl = this.projectApiService.selectPrjPrdDtlById(entity.getId());
			if(null!=dtl){
				Long prjId = dtl.getPrjId();
				if (prjId == null && entity.getPrjId() != null) {
					prjId = entity.getPrjId();
				}
				PrjBscInfoDTO prjBsc = 	this.projectApiService.selectPrjBscInfoById(prjId, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
				if(null!=prjBsc){
					orgCd = prjBsc.getBuOrgCd();
				}
			}
			//查询文件主code
			SysUlDatCfgQueryCondition qc = new SysUlDatCfgQueryCondition();
			List<String> codeList = new ArrayList<String>();
			codeList.add(PrjPrdMtgConstant.PRJ_PRD_MTG_FILE_CODE);
			qc.setCfgCdList(codeList);
			qc.setOrgCd(orgCd);
			qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
			String  sysCdStr = "";
			String orgCdStr = "";
			List<SysUlDatCfgVO> cfgList = sysUlDatCfgService.searchList(qc);
			sysCdStr = cfgList.get(0).getSysCd();
			orgCdStr = cfgList.get(0).getOrgCd();
			List<SysUlFilesRecVO> fileList = entity.getFileList();
			if(CollectionUtils.isNotEmpty(fileList)){
				SysUlFilesRecQueryCondition ulQc = new SysUlFilesRecQueryCondition();
				ulQc.setPkId(String.valueOf(entity.getId()));
				ulQc.setOrgCd(orgCdStr);
				ulQc.setSysCd(sysCdStr);
				ulQc.setCfgCd(PrjPrdMtgConstant.PRJ_PRD_MTG_FILE_CODE);
				ulQc.setCfgDtlCd(PrjPrdMtgConstant.PRJ_PRD_MTG_FILE_DETAIL_CODE);
				ulQc.setTabNm("PRJ_PRD_MTG_INFO");
				this.uploadApiService.removeSysUlFilesRecByCondition(ulQc);
				for (SysUlFilesRecVO sysUlFilesRecVO : fileList) {
					sysUlFilesRecVO.setPkId(String.valueOf(entity.getId()));
					sysUlFilesRecVO.setTabNm("PRJ_PRD_MTG_INFO");
					sysUlFilesRecVO.setIsDel(BaseConstant.IS_YESNO_NO);
					sysUlFilesRecVO.setOrgCd(orgCdStr);
					sysUlFilesRecVO.setSysCd(sysCdStr);
					sysUlFilesRecVO.setCfgCd(PrjPrdMtgConstant.PRJ_PRD_MTG_FILE_CODE);
					sysUlFilesRecVO.setCfgDtlCd(PrjPrdMtgConstant.PRJ_PRD_MTG_FILE_DETAIL_CODE);
					sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH)+sysUlFilesRecVO.getFilePath());

					/*SysUlFilesRecDTO dto = SysUlFilesRecVOTransform.toDTO(sysUlFilesRecVO);
					dtoFileList.add(dto);*/
					sysUlFilesRecService.add(sysUlFilesRecVO);
				}
			}
		} catch (Exception e) {
			BaseLogUtils.error(logger, "modify", "修改抵押信息,文件处理异常", CurrentThreadContext.getCurrentUserName(),e);
			return false;
		}

		return true;
		
	}

	@Override
	public List<KeyValueVO> getMtgPsnTypCdList() throws BaseException {
		return this.getKeyValueList(DictionaryConstant.CODE_MTG_PSN_TYP_CD);
	}
	@Override
	public List<KeyValueVO> getGuarTypCdList() throws BaseException {
		return this.getKeyValueList(DictionaryConstant.CODE_GUAR_TYP_CD);
	}
	@Override
	public List<KeyValueVO> getGuarStsCdList() throws BaseException {
		return this.getKeyValueList(DictionaryConstant.CODE_GUAR_STS_CD);
	}
	public List<KeyValueVO> getKeyValueList(String code) throws BaseException {
		List<KeyValueVO>  keyValueList = null;
		List<SysDictionaryDTO>  dictionaryList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd(),code);
		if(CollectionUtils.isNotEmpty(dictionaryList)){
			keyValueList = new ArrayList<>();
			for (SysDictionaryDTO sysDictionaryDTO : dictionaryList) {
				KeyValueVO keyValue = new KeyValueVO();
				keyValue.setKey(sysDictionaryDTO.getCode());
				keyValue.setValue(sysDictionaryDTO.getCodeNm());
				keyValueList.add(keyValue);
			}
		}
		return keyValueList;
	}

	@Override
	public List<KeyValueVO> getYesNoList() throws BaseException {
		return this.getKeyValueList(DictionaryConstant.CODE_SYS_YES_NO_CD);
	}

	@Override
	public void modifyGuarSts(PrjPrdMtgVO entity) throws BaseException {
		boolean flag = this.projectApiService.modifyPrjPrdMtg(PrjPrdMtgVOTransform.toDTO(entity));
	}

	@Override
	public boolean checkPrjPrdMtgRecNoExist(PrjPrdMtgQueryCondition qc) throws BaseException {
		String recNo = qc.getRecNo();
		boolean flag = false;
		GetPrjPrdMtgByRecNoRequest request = new GetPrjPrdMtgByRecNoRequest();
		request.setRecNo(recNo);
		ResponseData response = mortgateService.getPrjPrdMtgByRecNo(request);
		if(PreloanResultCodeEnum.SUCCESS.getCode().equals(response.getCode()) && null !=response.getData()){
			List<PrjPrdMtgDTO> mtgList =(List<PrjPrdMtgDTO>)response.getData();
			if(CollectionUtils.isNotEmpty(mtgList)){
				for (PrjPrdMtgDTO mtgDTO : mtgList) {
					String str = mtgDTO.getRecNo().trim();
					if((!mtgDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_03))
							&&(!mtgDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_05))
							&&(!mtgDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_12))
							&&(!mtgDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_14))
							&&(!mtgDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_16))
							&&(!mtgDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_22))
							&&str.equals(recNo)){
						flag = true;
						break;
					}
				}
			}
		}
		return flag;
	}
	
	/**
	 * 验证登记证-抵押我司页
	 */
	@Override
	public DataResultVO checkMtgPage(String prjPrdDtlId, String fileId, String orgCd) throws BaseException {

		DataResultVO dataResultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, "验证登记证抵押我司页通过");
		try {
			SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();

			qc.setPkId(prjPrdDtlId);// 项目产品明细id
			qc.setId(fileId);
			qc.setSysCd(CurrentThreadContext.getCurrentSysCd());// 系统代码
			BaseLogUtils.info(logger, "", "checkMtgPage-qc：" + JSON.toJSONString(qc));
			List<SysUlFilesRecDTO> searchSysUlFilesRecList = this.uploadApiService.searchSysUlFilesRecList(qc);
			BaseLogUtils.info(logger, "",
					"this.uploadApiService.searchSysUlFilesRecList(qc):" + JSON.toJSONString(searchSysUlFilesRecList));
			if (searchSysUlFilesRecList == null || searchSysUlFilesRecList.size() == 0) {
				dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
				dataResultVO.setInfo("文件记录数据库记录不存在：" + JSON.toJSONString(qc));
				return dataResultVO;
			}

			for (SysUlFilesRecDTO sysUlFilesRecDTO : searchSysUlFilesRecList) {
				if (prjPrdDtlId.equals(sysUlFilesRecDTO.getPkId())) {// 上传记录表和抵押表id相同

					if("1".equals(sysUlFilesRecDTO.getFileRem())) {
						dataResultVO.setInfo("已验证登记证抵押我司页 " );
						return dataResultVO;
					}
					
					String filePath = sysUlFilesRecDTO.getAbsLocPath();// 服务器文件路径
//				 String filePath = "E:\\信审\\登记证-抵押页.jpg";//本地图片验证（失败）

					DataResultDTO dataResultDTO = this.checkVehicleRegistrationApiService.checkVehicleRegistration(filePath,
							Long.valueOf(prjPrdDtlId), 1L);
					BaseLogUtils.info(logger, "", "抵押证校验结果：this.checkVehicleRegistrationApiService.checkVehicleRegistration"
							+ JSON.toJSONString(dataResultDTO));

					/**
					 * code:00000,message：通过全部校验，真登记本，真抵押信息。
					 * code:30000,message：格式检查未通过-图片小于7M，请检查扫描仪设置
					 */
					SysUlFilesRecDTO sysUlFilesRec = new SysUlFilesRecDTO();
					String code = dataResultDTO.getCode();
					String info = dataResultDTO.getInfo();
					// code = "10000";
					if ("00000".equals(code)) {
						// 校验通过
						sysUlFilesRec.setFileRem("1");// 附件审核通过
					} else if ("0".equals(code) || "10000".equals(code) 
							|| "20000".equals(code) || "30000".equals(code)) {
						// 上传格式不正确，请重新上传
						sysUlFilesRec.setFileRem("2|"+ info);// 附件审核不通过
						dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
						dataResultVO.setInfo("上传格式不正确，请重新上传 " + info);
					} else {
						// 校验不通过
						sysUlFilesRec.setFileRem("3|"+ info);// 附件审核不通过
						dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
						dataResultVO.setInfo("验证结果为不一致，请再次确认是否提交 " + info);
						dataResultVO.setData("confirmPass");
					}
					
					
					List<SysUlFilesRecDTO> sysUlFilesRecDTOList = new ArrayList<SysUlFilesRecDTO>();
					sysUlFilesRec.setId(sysUlFilesRecDTO.getId());
					sysUlFilesRecDTOList.add(sysUlFilesRec);
					this.uploadApiService.modifySysUlFilesRecList(sysUlFilesRecDTOList);

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			BaseLogUtils.error(logger, "","PrjPrdMtgServiceImpl.checkMtgPage，识别抵押我司页异常:" + e.getMessage());
			
			dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
			dataResultVO.setInfo("识别抵押我司页异常，请再次确认是否提交 ");
			dataResultVO.setData("confirmPass");
		}
		return dataResultVO;
	}

	@Override
	public DataResultVO modifyFileRem(String fileId) throws BaseException {
		DataResultVO dataResultVO = new DataResultVO(BaseConstant.IS_YESNO_YES);
		SysUlFilesRecDTO sysUlFilesRecDTO = this.uploadApiService.selectBySysUlFilesRecId(Long.valueOf(fileId));
		if (sysUlFilesRecDTO != null) {
			sysUlFilesRecDTO.setFileRem("4");
			List<SysUlFilesRecDTO> sysUlFilesRecDTOList = new ArrayList<SysUlFilesRecDTO>();
			sysUlFilesRecDTOList.add(sysUlFilesRecDTO);
			uploadApiService.modifySysUlFilesRecList(sysUlFilesRecDTOList);
		}
		return dataResultVO;
	}

	 @Override
    public void modifyFileState(String id) throws BaseException {
        
        SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
        qc.setPkId(id);//抵押id=项目产品明细id
        qc.setCfgCd(PrjBscInfoConstant.CODE_PRJ_PRD_FILE_CD);
//        qc.setCfgDtlCd("13");
        qc.setTabNm(PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_TABLE_NM);
        qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
        
        List<SysUlFilesRecDTO> sysUlFilesRecDTOList = this.uploadApiService.searchSysUlFilesRecList(qc);
        BaseLogUtils.info(logger, null, "sysUlFilesRecDTOList:" + JSON.toJSONString(sysUlFilesRecDTOList));
        if(sysUlFilesRecDTOList != null && sysUlFilesRecDTOList.size() >0) {
            for (SysUlFilesRecDTO sysUlFilesRecDTO : sysUlFilesRecDTOList) {
                sysUlFilesRecDTO.setAudStsCd("1");//验证通过
            }
            
            this.uploadApiService.modifySysUlFilesRecList(sysUlFilesRecDTOList);
        }
    }
}

	
